<template>
  <div class="user-info-container">
    <el-card
      class="box-card"
      :class="{ 'card-hover': isCardHovered }"
      @mouseenter="isCardHovered = true"
      @mouseleave="isCardHovered = false"
    >
      <h2 class="title">
        <span class="title-text">用户信息</span>
        <div class="title-underline"></div>
      </h2>

      <div class="img">
        <el-image
          :src="image_url || 'https://empty'"
          class="avatar-img"
          :class="{ 'avatar-pulse': isImageLoading }"
          @load="handleImageLoad"
          fit="cover"
        />
        <div
          class="image-over"
          :class="{ isOver: isShow }"
          @mouseleave="isShow = false"
          @mouseenter="isShow = true"
          @click="handleImageClick"
        >
          <el-icon size="60" v-if="isShow">
            <Camera class="camera-icon" />
          </el-icon>
          <span v-if="isShow" class="upload-text">点击更换头像</span>
        </div>
      </div>

      <transition-group name="list">
        <div
          class="user-info-item"
          v-for="(item, index) in userInfo"
          :key="index"
          :class="{ 'item-highlight': isEditing[index] }"
        >
          <span class="info-label">{{ item.label }}</span>
          <span
            v-if="!isEditing[index]"
            class="info-value"
            :class="{ 'value-hover': item.edit === 'true' }"
          >
            <template v-if="['college', 'major', 'class'].includes(item.prop)">
              <div class="multi-value-container">
                <span
                  v-for="(value, idx) in item.value.split(',')"
                  :key="idx"
                  class="multi-value-item"
                >
                  {{ value.trim() }}
                </span>
              </div>
            </template>
            <template v-else>
              {{ item.value }}
            </template>
          </span>
          <div v-else class="edit-content">
            <!-- ****************用户信息 ****************-->
            <el-input
              v-if="item.type == 'input'"
              v-model="userInfo[index].value"
              :placeholder="`请输入${item.label}`"
            ></el-input>
            <!-- 选择性别 -->
            <el-select
              v-else-if="item.type == 'selectGender'"
              v-model="userInfo[index].value"
              placeholder="请选择"
              style="width: 150px"
            >
              <el-option
                v-for="(item, index) in genderOpt"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <!-- 学院选择 -->
            <el-select
              v-else-if="item.type == 'selectCollege'"
              v-model="userInfo[index].value"
              placeholder="请选择"
              style="width: 150px"
              @change="getMajor"
            >
              <el-option
                v-for="(item, index) in collegeOpt"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <!-- 专业选择 -->
            <el-select
              v-else-if="item.type == 'selectMajor'"
              v-model="userInfo[index].value"
              placeholder="请先选择学院，在选择专业"
              style="width: 150px"
              @change="getClassList"
            >
              <el-option
                v-for="(item, index) in majorOpt"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <!-- 班级选择 -->
            <el-select
              v-else-if="item.type == 'selectClass'"
              v-model="userInfo[index].value"
              placeholder="请先选择专业，在选择班级"
              style="width: 150px"
            >
              <el-option
                v-for="(item, index) in classOpt"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <!-- **************************** -->
            <div class="button-group">
              <el-button type="primary" @click="saveEditedValue(index, item)" :loading="isSaving">
                {{ isSaving ? '保存中...' : '保存' }}
              </el-button>
              <el-button @click="cancelEditing(index)">取消</el-button>
            </div>
          </div>
          <el-icon
            v-if="!isEditing[index] && item.edit == 'true'"
            class="edit-icon"
            @click="startEditing(index)"
          >
            <Edit />
          </el-icon>
        </div>
      </transition-group>
    </el-card>
    <!-- 用户上传头像 -->
    <el-dialog v-model="dialogVisible" title="用户上传头像" width="800" class="upload-dialog">
      <el-upload
        class="upload-demo"
        drag
        action="http://127.0.0.1:3007/info/uploadAvatar"
        :on-success="handleUploadSuccess"
        :limit="1"
        ref="uploadRaef"
        :headers="{ authorization: userStore.token }"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">拖拽文件<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">jpg/png files with a size less than 500kb</div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import { useUserStore } from '@/stores/user'
import { showStatusMessage } from '@/utils/common/showMessage'
import {
  bindAvatarApi,
  editUserInfoApi,
  getClassApi,
  getCollegeApi,
  getMajorApi
} from '@/api/baseData'
import { loginApi } from '@/api/login'
import { getKey, removeKey, setKey } from '@/utils/common/localStorage'
import { ElLoading } from 'element-plus'
const genderOpt = [
  { label: '男', value: '男' },
  { label: '女', value: '女' }
]
const collegeOpt = ref([])
const college = ref('')
// 获取学院列表
async function getCollege() {
  const res = await getCollegeApi()
  collegeOpt.value = res.data.map((item) => {
    return {
      label: item.college,
      value: item.college
    }
  })
}
getCollege()
// 获取专业列表
const majorOpt = ref([])
async function getMajor(data) {
  college.value = data
  const res = await getMajorApi({ college: data })
  console.log(res)
  majorOpt.value = res.data?.map((item) => {
    return {
      label: item.major,
      value: item.major
    }
  })
}
// 获取班级列表
const classOpt = ref([])
async function getClassList(data) {
  const res = await getClassApi({ college: college.value, major: data })
  console.log(res)
  classOpt.value = res.data?.map((item) => {
    return {
      label: item.class,
      value: item.class
    }
  })
  console.log(classOpt.value)
}

// *****************获取用户信息数据****************
const userStore = useUserStore()
const data = userStore.userInfo
const image_url = ref(userStore.image_url)

const userInfo = ref([])

const switchData = (item, data) => {
  let value = null
  switch (item) {
    case 'enterpriseAddress':
      value = JSON.parse(data).join(',')
      break
    case 'class':
    case 'major':
    case 'college':
      value = Array.isArray(data) ? data.join(',') : data
      break
    default:
      value = data
  }
  return value
}

function initData() {
  const arr = []
  let result = ''
  let edit = 'true'
  let type = 'input'
  for (let item in data) {
    if (item == 'id') {
      continue
    } else if (item == 'image_url') {
      continue
    } else if (item == 'status') {
      continue
    } else if (item == 'permission') {
      continue
    } else if (item == 'account') {
      result = '账号'
      edit = 'false'
    } else if (item == 'identity') {
      result = '身份'
      edit = 'false'
    } else if (item == 'enterpriseName') {
      result = '企业名称'
    } else if (item == 'studentNumber') {
      result = '学号'
    } else if (item == 'name') {
      result = '姓名'
    } else if (item == 'phone') {
      result = '联系电话'
    } else if (item == 'college') {
      result = '学院'
      type = 'selectCollege'
    } else if (item == 'major') {
      result = '专业'
      type = 'selectMajor'
    } else if (item == 'class') {
      // 如果是admin账号，跳过班级字段
      if (userStore.userInfo.identity == '管理员') {
        continue
      }
      result = '班级'
      type = 'selectClass'
    } else if (item == 'gender') {
      result = '性别'
      type = 'selectGender'
    } else if (item == 'teacherNumber') {
      result = '教职工号'
    } else if (item == 'enterpriseAddress') {
      result = '企业地址'
    } else if (item == 'detailAddress') {
      result = '详细地址'
    } else if (item == 'enterpriseAddress') {
      result = '企业地址'
    } else if (item == 'industry') {
      result = '所属行业'
    } else if (item == 'detail') {
      result = '企业详情'
    }

    let obj = {
      label: result,
      value: switchData(item, data[item]),
      prop: item,
      edit: edit,
      type: type
    }
    arr.push(obj)
  }
  userInfo.value = arr
}
initData()

// 用于记录每个信息项是否处于编辑状态的数组
const isEditing = ref(Array(userInfo.length).fill(false))

// 开始编辑指定索引的信息项
const startEditing = (index) => {
  isEditing.value[index] = true
}

// 取消编辑指定索引的信息项，直接变回文本框
const cancelEditing = (index) => {
  isEditing.value[index] = false
}
const identity = userStore.userInfo.identity
// 保存编辑后的信息值并发送给后端，然后变回文本框
const saveEditedValue = async (index, data) => {
  let loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  try {
    const res = await editUserInfoApi({
      identity,
      prop: data.prop,
      value: data.value,
      account: userStore.userInfo.account
    })
    showStatusMessage(res)
    // 重新获取个人信息
    console.log(userInfo.value[0].value)

    console.log(1)
    const userinfoRes = await loginApi({
      account: userStore.userInfo.account,
      identity: userStore.userInfo.identity
    })
    console.log(2)

    // 删除token，重新设置token
    removeKey('token')
    console.log(1)
    setKey('token', userinfoRes.token)
    console.log(getKey('token'))

    console.log(2)

    // 因为在removeKey('token')后,userStore中的token还未更新,
    // 而userinfoRes.token是新的token值,所以它们不相等
    // 更新userStore中的token
    userStore.token = userinfoRes.token

    console.log(userStore.token === userinfoRes.token)
    console.log(userStore.token)
    console.log(userinfoRes.token)

    // 重新设置用户信息
    await userStore.getUserInfo()
    isEditing.value[index] = false
    loading.close()
  } catch (error) {
    // console.error('保存用户信息时出错：', error)
    showStatusMessage({ status: 1, message: error })
    loading.close()
  }
}

// 头像处理
const isShow = ref(false)
const dialogVisible = ref(false)
const uploadRaef = ref(null)
function handleImageClick() {
  dialogVisible.value = true
}

// 文件上传成功的处理
async function handleUploadSuccess(e) {
  const res = await bindAvatarApi({
    account: data.account,
    onlyId: e.onlyId,
    url: e.url,
    identity: userStore.userInfo.identity
  })
  userStore.resetGetInfo()
  showStatusMessage(res)
  dialogVisible.value = false
  uploadRaef.value.clearFiles()
  // 更新用户信息
  userStore.$patch({
    image_url: e.url
  })
  nextTick(() => {
    image_url.value = userStore.image_url
  })
}
</script>

<style scoped>
.user-info-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  background: linear-gradient(120deg, #e0c3fc 0%, #8ec5fc 100%);
  /* padding: 20px 20px 130px; */
}

.box-card {
  width: 700px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: none;
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.15);
  border-radius: 20px;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: scroll;
  margin: 15px auto 30px;
  padding: 20px;
}

.card-hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 40px rgba(31, 38, 135, 0.25);
}

.title {
  position: relative;
  text-align: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
}

.title-text {
  font-size: 28px;
  font-weight: 600;
  background: linear-gradient(45deg, #4b6cb7, #182848);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  position: relative;
}

.title-text::after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 50%;
  width: 50px;
  height: 3px;
  background: linear-gradient(45deg, #4b6cb7, #182848);
  transform: translateX(-50%) scaleX(0);
  transition: transform 0.3s ease;
}

.card-hover .title-text::after {
  transform: translateX(-50%) scaleX(1);
}

.user-info-item {
  display: flex;
  align-items: center;
  padding: 8px 15px;
  margin-bottom: 10px;
  border-radius: 8px;
  background: transparent;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.user-info-item::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 4px;
  height: 100%;
  background: #4b6cb7;
  transform: scaleY(0);
  transition: transform 0.3s ease;
}

.user-info-item:hover::before {
  transform: scaleY(1);
}

.info-label {
  min-width: 100px;
  font-size: 15px;
  color: #4b6cb7;
  font-weight: 500;
  transition: all 0.3s ease;
  position: relative;
  padding-left: 10px;
}

.info-value {
  flex: 1;
  font-size: 16px;
  color: #333;
  transition: all 0.3s ease;
  padding: 6px 12px;
  border-radius: 8px;
}

.multi-value-container {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  padding: 2px 0;
}

.multi-value-item {
  background: linear-gradient(135deg, #4b6cb7 0%, #182848 100%);
  color: white;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 13px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.multi-value-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.1);
  transform: translateX(-100%);
  transition: transform 0.3s ease;
}

.multi-value-item:hover::before {
  transform: translateX(0);
}

.multi-value-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(75, 108, 183, 0.2);
}

.edit-icon {
  cursor: pointer;
  color: #4b6cb7;
  font-size: 18px;
  transition: all 0.3s ease;
  opacity: 0;
  transform: translateX(10px);
}

.user-info-item:hover .edit-icon {
  opacity: 1;
  transform: translateX(0);
}

.edit-icon:hover {
  transform: rotate(15deg) scale(1.1);
  color: #182848;
}

.button-group {
  display: flex;
  gap: 8px;
  margin-left: 10px;
}

.button-group .el-button {
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.button-group .el-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.2);
  transform: translateX(-100%) rotate(45deg);
  transition: transform 0.6s ease;
}

.button-group .el-button:hover::before {
  transform: translateX(100%) rotate(45deg);
}

.img {
  position: relative;
  width: 200px;
  height: 200px;
  margin: 0 auto 20px;
  cursor: pointer;
}

.avatar-img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  transition: all 0.3s ease;
}

.image-over {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0);
  transition: all 0.3s ease;
}

.isOver {
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(2px);
}

.camera-icon {
  color: white;
  margin-bottom: 10px;
  transform: translateY(-20px);
  opacity: 0;
  transition: all 0.3s ease;
}

.isOver .camera-icon {
  transform: translateY(0);
  opacity: 1;
}

.upload-text {
  color: white;
  font-size: 16px;
  transform: translateY(20px);
  opacity: 0;
  transition: all 0.3s ease 0.1s;
}

.isOver .upload-text {
  transform: translateY(0);
  opacity: 1;
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.05);
    opacity: 0.8;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

.avatar-pulse {
  animation: pulse 2s infinite;
}

/* 添加列表动画 */
.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease;
}

.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}

.user-info-item:last-child {
  margin-bottom: 15px;
}


</style>
